package ias.deepsearch.com.helper.util.normal;

import android.os.Environment;
import android.util.Log;

import com.socks.library.KLog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import ias.deepsearch.com.helper.util.ACache;

/**
 * Created by vector on 16/9/22.
 */
public class FileUtil {

    //获取支持的应用的信息（计算应用的md5值）
    public static List<String> getApkMD5List(){
        List<String> results = new ArrayList<>();
        String base_path = "/data/app/";
        String[] suffix = {"-1/base.apk", "-2/base.apk"};
        for(int i = 0; i < Constants.packages.length; i++){
            for(int j = 0; j < suffix.length; j++){
                String nowFilePath = base_path + Constants.packages[i] + suffix[j];
                File nowFile = new File(nowFilePath);
                if(nowFile.exists()){
                    String md5 = MD5Calculator.calMD5(nowFilePath);
                    results.add(md5);
                    KLog.v(Constants.NORMAL_TAG, nowFilePath + " : " + md5);
                }
            }
        }
        return results;
    }

    //获取支持的应用的信息（计算应用的md5值）
    public static String getApkMD5(String package_name){
        String result="";
        String base_path = "/data/app/";
        String[] suffix = {"-1/base.apk", "-2/base.apk"};
        for(int j = 0; j < suffix.length; j++){
            String nowFilePath = base_path + package_name + suffix[j];
            File nowFile = new File(nowFilePath);
            if(nowFile.exists()){
                String md5 = MD5Calculator.calMD5(nowFilePath);
                result = md5;
                KLog.v(Constants.NORMAL_TAG, nowFilePath + " : " + md5);
            }
        }
        return result;
    }


    //获取本地引擎列表
    public static List<String> getLocalEngines(){
        List<String> engines = new ArrayList<>();
        File file = new File(Constants.LOCAL_ENGINE_PATH);
        if(file.exists() && file.isDirectory()){
            File[] files = file.listFiles();
            if(files != null){
                for(int i = 0; i < files.length; i++){
                    //KLog.v(Constants.NORMAL_TAG, files[i].getName());
                    if(files[i].isFile() && files[i].getName().endsWith(".dex")){
                        KLog.v(Constants.NORMAL_TAG, files[i].getName());
                        engines.add(files[i].getName());
                    }
                }
            }
        }else{
            KLog.v(Constants.NORMAL_TAG, "====no such directory=====");
        }
        return engines;
    }


    public static void writeFileToSD(String fileName, String content) {
        String sdStatus = Environment.getExternalStorageState();
        if(!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
            Log.d("TestFile", "SD card is not avaiable/writeable right now.");
            return;
        }
        try {
            String pathName="/sdcard/ias/";
            File path = new File(pathName);
            File file = new File(pathName + fileName);
            if( !path.exists()) {
                Log.d("TestFile", "Create the path:" + pathName);
                path.mkdir();
            }
            if( !file.exists()) {
                Log.d("TestFile", "Create the file:" + fileName);
                file.createNewFile();
            }
            FileOutputStream stream = new FileOutputStream(file);
            byte[] buf = content.getBytes();
            stream.write(buf);
            stream.close();

        } catch(Exception e) {
            Log.e("TestFile", "Error on writeFilToSD.");
            e.printStackTrace();
        }
    }

    public static ACache getACache() {
        String path = "/sdcard/ias/";
        File tmp = new File(path);
        if(!tmp.exists()){
            tmp.mkdir();
        }
        ACache aCache = ACache.get(new File(path, "ias"));
        return aCache;
    }


    public static String getContent(String filePath){
        File file = new File(filePath);
        if(!file.exists())
            return "";
        String res="";
        try{
            FileInputStream fin = new FileInputStream(filePath);

            int length = fin.available();

            byte [] buffer = new byte[length];
            fin.read(buffer);

            res = new String(buffer, "UTF-8");

            fin.close();
        }

        catch(Exception e){
            e.printStackTrace();
        }
        return res;
    }


    private static Set<File> visitedFile;

    public static long getDirSize(File f) {
        visitedFile = new HashSet<File>();
        return internalGetSize(f);

    }

    private static long internalGetSize(File f) {
        try {
            f = f.getCanonicalFile();

            if (visitedFile.contains(f))
                return 0;
            visitedFile.add(f);
            if (f.isDirectory()) {
                long ret = 0;
                for (File subF : f.listFiles()) {
                    ret += getDirSize(subF);
                }
                return ret;
            } else
                return f.length();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static byte[] getBytes(String fileName) {
        try {
            File f = new File(fileName);
            byte[] ret = new byte[(int)f.length()];
            FileInputStream fin = new FileInputStream(f);
            fin.read(ret);
            return ret;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
